package com.txby.platformCore.component.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.net.ssl.SSLContext;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;

import com.alibaba.druid.support.json.JSONUtils;


/**
 * 调用优酷API的工具类
 * @author liuzq
 *
 */
public class YoukuVideoUtils {
	
	// 我上传的视频(videos/by_me)
	public final static String  MY_UPLOAD_VIDEO_LIST="https://api.youku.com/videos/by_me.json";
	// 刷新Access Token(oauth2/token)
	public final static String  GET_MY_LATEST_ACCESS_TOKEN="https://api.youku.com/oauth2/token.json";
	// 单条视频详细信息(videos/show)
	public final static String GET_SINGLE_VIDEO_DETAIL ="https://api.youku.com/videos/show.json";
	// 应用Key
	public final static String CLIENT_ID = "8711ca42bf58b526";
	// 授权令牌
	public final static String ACCESS_TOKEN = "1b5eb0bcc3dbbd384af7a4027701edf8";
	// 刷新令牌
	public final static String REFRESH_TOKEN = "8e3f4e409a8df5235d732bec7f63093d";
	
	
	/**
	 * 获取http或者https协议的get请求
	 * 
	 * @param scheme http或者https
	 * @param host 主机地址
	 * @param port 端口 不需要设置时请传负整数
	 * @param path 路径
	 * @param nvps 要传的参数
	 * @param needValidKeys 值不能为空的参数key
	 * @return HttpGet
	 * @throws URISyntaxException
	 */
	public static HttpGet getHttpGet(String scheme,String host,int port,String path,List <NameValuePair> nvps,List<String> needValidKeys) throws URISyntaxException {
		if(HttpGet.METHOD_NAME.equalsIgnoreCase(scheme) && HttpPost.METHOD_NAME.equalsIgnoreCase(scheme)) {
			throw new IllegalArgumentException("请求的协议不合法");
		}
		if(StringUtils.isBlank(host)) {
			throw new IllegalArgumentException("主机名host不能为空,host值:"+host);
		}
		if(StringUtils.isBlank(path)) {
			throw new IllegalArgumentException("path不能为空,path值:"+path);
		}
		URI uri = new URIBuilder()
		        .setScheme(scheme)
		        .setHost(host)
		        .setPort(port)
		        .setPath(path)
		        .setParameters(nvps)
		        .build();
		//添加参数
		HttpGet httpget = new HttpGet(uri);
		return httpget;
	}
	
	/**
	 * 获取http或者https协议的post请求
	 * 
	 * @param scheme http或者https
	 * @param host 主机地址
	 * @param port 端口 不需要设置时请传负整数
	 * @param path 路径
	 * @param nvps 要传的参数
	 * @param needValidKeys 值不能为空的参数key
	 * @return HttpPost
	 * @throws URISyntaxException
	 */
	public static HttpPost getHttpPost(String scheme,String host,int port,String path,List <NameValuePair> nvps,List<String> needValidKeys) throws URISyntaxException {
		if(HttpGet.METHOD_NAME.equalsIgnoreCase(scheme) && HttpPost.METHOD_NAME.equalsIgnoreCase(scheme)) {
			throw new IllegalArgumentException("请求的协议不合法");
		}
		if(StringUtils.isBlank(host)) {
			throw new IllegalArgumentException("主机名host不能为空,host值:"+host);
		}
		if(StringUtils.isBlank(path)) {
			throw new IllegalArgumentException("path不能为空,path值:"+path);
		}
		
		URI uri = new URIBuilder()
				.setScheme(scheme)
				.setHost(host)
				.setPort(port)
				.setPath(path)
		        .setParameters(nvps)
				.build();
		HttpPost httpPost = new HttpPost(uri);
		
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(nvps,HTTP.UTF_8));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return httpPost;
	}
	

	/**http类型
     * 创建一个可以访问Http类型URL的工具类，
     * 返回一个CloseableHttpClient实例
     */
    public static CloseableHttpClient createClientDefault() {
        return HttpClients.createDefault();
    }
	
	/**https类型
     * 创建一个可以访问Https类型URL的工具类，
     * 返回一个CloseableHttpClient实例
     */
    public static CloseableHttpClient createSSLClientDefault() {
        try {
            SSLContext sslContext=new SSLContextBuilder().loadTrustMaterial(
                    null,new TrustStrategy() {
                        //信任所有
                        public boolean isTrusted(X509Certificate[] chain, String authType)
                                throws CertificateException {
                            return true;
                        }
                    }).build();
            SSLConnectionSocketFactory sslsf=new SSLConnectionSocketFactory(sslContext);
            return HttpClients.custom().setSSLSocketFactory(sslsf).build();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        }
        return HttpClients.createDefault();
    }
    
    /**
     * 
     * @param args
     * @throws Exception
     */
    @SuppressWarnings("rawtypes")
	public static String getLatestToken() {
    	// 自动刷新token https://api.youku.com/oauth2/token.json
        CloseableHttpClient httpClient0 =createSSLClientDefault();   
        HttpPost httpPost=null;
        CloseableHttpResponse response0 = null;
        String html0 = null;
        List<NameValuePair> params0=new ArrayList<NameValuePair>();
        params0.add(new BasicNameValuePair("client_id",CLIENT_ID));
        params0.add(new BasicNameValuePair("grant_type","refresh_token"));
        params0.add(new BasicNameValuePair("refresh_token",REFRESH_TOKEN));
        try {
			httpPost= getHttpPost("https","api.youku.com",-1,"/oauth2/token.json",params0,null);
			response0 = httpClient0.execute(httpPost);
			HttpEntity entity0 =response0.getEntity();
			html0 = EntityUtils.toString(entity0);
			Map m = (Map) JSONUtils.parse(html0);
			return (String) m.get("access_token");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				response0.close();
				httpClient0.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
    }
    
	public static void main(String[] args) throws Exception {
		System.out.println(getLatestToken());
		// 自动刷新token https://api.youku.com/oauth2/token.json
        CloseableHttpClient httpClient0 =createSSLClientDefault();   
        HttpPost httpPost=null;
        List<NameValuePair> params0=new ArrayList<NameValuePair>();
        params0.add(new BasicNameValuePair("client_id",CLIENT_ID));
        params0.add(new BasicNameValuePair("grant_type","refresh_token"));
        params0.add(new BasicNameValuePair("refresh_token",REFRESH_TOKEN));
        httpPost= getHttpPost("https","api.youku.com",-1,"/oauth2/token.json",params0,null);
        CloseableHttpResponse response0=httpClient0.execute(httpPost);
        //打印响应的到的html正文
        HttpEntity entity0 =response0.getEntity();
        String html0=EntityUtils.toString(entity0);
        System.out.println(html0);
        //关闭连接
        response0.close();
        httpClient0.close();
		
		
		// list
        CloseableHttpClient httpClient =createSSLClientDefault();   
        HttpGet httpGet=null;
        List<NameValuePair> params=new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("client_id",CLIENT_ID));
        params.add(new BasicNameValuePair("access_token",ACCESS_TOKEN));
        httpGet= getHttpGet("https","api.youku.com",-1,"/videos/by_me.json",params,null);
        CloseableHttpResponse response=httpClient.execute(httpGet);
        //打印响应的到的html正文
        HttpEntity entity =response.getEntity();
        String html=EntityUtils.toString(entity);
        System.out.println(html);
        //关闭连接
        response.close();
        httpClient.close();
        
        
    	// 单个	https://api.youku.com/videos/show.json
        CloseableHttpClient httpClient1 =createSSLClientDefault();   
        HttpGet httpGet1=null;
        List<NameValuePair> params1=new ArrayList<NameValuePair>();
        params1.add(new BasicNameValuePair("client_id",CLIENT_ID));
        params1.add(new BasicNameValuePair("video_id", "XMjc4ODM2MjI0NA=="));
        params1.add(new BasicNameValuePair("ext", "66666666"));
        httpGet1= getHttpGet("https","api.youku.com",-1,"/videos/show.json",params1,null);
        CloseableHttpResponse response1=httpClient1.execute(httpGet1);
        //打印响应的到的html正文
        HttpEntity entity1 =response1.getEntity();
        String html1=EntityUtils.toString(entity1);
        System.out.println(html1);
        //关闭连接
        response1.close();
        httpClient1.close();
        
        
	}

}
